<template>
    <div class="container">
        <a-page-header style="background-color: transparent;" title="管理" @back="() => router.back()" />
        <div class="set">
            <div :class="`item setItem${index + 1}`" v-for="(item, index) in setItem" :key="item.title"
                :style="{ gridArea: item.gridArea }" @click="item.clickFn">
                <img :src="item.img" alt="">
                {{ item.title }}
            </div>
        </div>

        <a-modal title="提示" centered v-model:open="openFlag" width="80%" @ok="open" @cancel="openFlag = false">
            <p style="font-size: .5rem;">此操作不会记录取标本记录，仅供特殊情况下使用，是否继续？</p>
        </a-modal>

        <a-modal title="提示" :footer="null" centered v-model:open="timeFlag" width="80%" @ok="timeFlag = false">
            <p style="font-size: .5rem;">消毒时间剩余 {{ time }} 秒</p>
        </a-modal>

        <a-modal title="取标本" centered v-model:open="testTubeFlag" @ok="takeTestTube">
            <p style="font-size: .35rem;">姓名：{{ name }}</p>
            <p style="font-size: .35rem;">科室：{{ department }}</p>
            <p style="font-size: .35rem;">取样数量：{{ currentTestTubeNum }}</p>
        </a-modal>

        <a-modal title="提示" centered v-model:open="closeDoorFlag" width="80%" :footer="null" :closabled="false">
            <p style="font-size: .35rem;">请取出标本后点击关门按钮</p>
            <a-button type="primary" block @click="closeDoorFn">关门</a-button>
        </a-modal>
    </div>
</template>
<script setup lang="ts">
import { useRouter } from 'vue-router';
import { getTime, isAndroid } from '@/utils/UtilFun';
import { computed, h, onMounted, onUnmounted, reactive, ref } from 'vue';
import { db } from '@/utils/DexieDB'

import out from '../assets/img/takeTestTube.png'
import disfect from '../assets/img/disin.png'
import openDoor from '../assets/img/open.png'
import closeDoor from '../assets/img/close.png'
import set from '../assets/img/setting.png'
import { useIntervalFn } from '@vueuse/core';
import { liveQuery } from 'dexie';
import { addAlarmApi, addDisinfectApi, queryServiceNurseApi, uploadOutsFileApi } from '@/API/API';
import { base64ToFile } from '@/utils/UtilFun';

const router = useRouter()
const code = router.currentRoute.value.query.code as string
const permission = router.currentRoute.value.query.permission as string

const device = ref<device | null>(null)

const openFlag = ref(false)
const timeFlag = ref(false)
const testTubeFlag = ref(false)
const closeDoorFlag = ref(false)
const currentTestTubeNum = ref(0)
const disinfectAutoMode = ref(false)
const disinfectTime = ref(0)
const time = ref(0)

const isClosedTime = ref(0)

const name = ref('');
const department = ref('');

const nurse = ref<nurse | null>(null)



let timer: any = null, isClosed = true


const setItem = reactive([
    {
        title: '取标本',
        gridArea: 'a',
        img: out,
        clickFn: async () => {
            window.ClosetAndroid.ttsStop();
            if (currentTestTubeNum.value === 0) {
                window.ClosetAndroid.ttsSpeak('当前暂无试管！', 1);
            } else {
                testTubeFlag.value = true
            }
        }
    },
    {
        title: '消毒',
        gridArea: 'e',
        img: disfect,
        clickFn: () => {
            disinfect()
        }
    },
    {
        title: '开门',
        gridArea: 'b',
        img: openDoor,
        clickFn: () => {
            openFlag.value = true
        }
    },
    {
        title: '关门',
        gridArea: 'c',
        img: closeDoor,
        clickFn: () => {
            if (!isClosed && isAndroid()) {
                isClosed = true
            }
            // window.ClosetAndroid.closeTrackLock();
            window.ClosetAndroid.closeTrack();
        }
    },
    {
        title: '设置',
        gridArea: 'd',
        img: set,
        clickFn: () => {
            if (!isClosed) {
                window.ClosetAndroid.ttsSpeak('请先关闭仓门！', 1);
                return
            } else if (permission === '管理') {
                router.push('/SetItem')
            } else {
                window.ClosetAndroid.ttsSpeak('您无管理权限，请联系管理员', 1);
            }
        }
    },
    {
        title: '测试',
        gridArea: '.',
        img: set,
        clickFn: () => {
            // router.push('/Test')
            window.ClosetAndroid.deletePhoto()
        }
    },
])

// 开门
function open() {
    openFlag.value = false
    isClosed = false
    if (isAndroid()) {
        // window.ClosetAndroid.openTrackLock();
        window.ClosetAndroid.openTrack();
    }
    //     readClosedTimer = setInterval(() => {
    //         window.ClosetAndroid.readTrackLock()
    //     }, 1000)
}
// 关门
function closeDoorFn() {
    closeDoorFlag.value = false
    clearTimer()
    isClosed = true
    // window.ClosetAndroid.closeTrackLock();
    window.ClosetAndroid.closeTrack();
    timer = setInterval(() => {
        router.back()
    }, device.value!.backViewTimeOut * 1000 * 60)
}
// 开消杀
function openKill() {
    if (isAndroid()) {
        if (!isClosed) {
            window.ClosetAndroid.ttsSpeak('请先关闭仓门！', 1);
        } else {
            window.ClosetAndroid.OpenkillVirus();
        }
    }
}
// 关消杀
function closeKill() {
    if (isAndroid()) {
        window.ClosetAndroid.closekillVirus();
    }
}
// 取标本
function takeTestTube() {
    console.log('去标本');
    testTubeFlag.value = false
    closeDoorFlag.value = true
    // window.ClosetAndroid.openTrackLock()
    window.ClosetAndroid.openTrack()
    window.ClosetAndroid.takePhoto('out');
    isClosed = false
    clearTimer()
    timer = setInterval(() => {
        isClosedTime.value++
        window.ClosetAndroid.readTrackLockLocation()
        if (isClosedTime.value > 60) {
            clearTimer()
            // window.ClosetAndroid.closeTrackLock();
            window.ClosetAndroid.closeTrack();
            addAlarm('取样超时报警')
            timer = setInterval(() => {
                router.back()
            }, device.value!.backViewTimeOut * 1000 * 60)
        }
    }, 1000);
}
// 消毒
function disinfect() {
    if (!isClosed && isAndroid()) {
        window.ClosetAndroid.ttsSpeak('请先关闭仓门！', 1);
        return
    }
    if (disinfectAutoMode.value) {
        window.ClosetAndroid.ttsSpeak('当前模式为自动，请切换模式！', 1);
    } else if (currentTestTubeNum.value !== 0) {
        window.ClosetAndroid.ttsSpeak('请先取出标本再消毒！', 1);
    } else {
        // 发送消毒数据
        db.disinfect.add({
            time: getTime(),
            info: '手动模式消毒'
        }).then((id) => {
            return db.disinfect.get(id)
        }).then((data) => {
            openKill()
            addDisinfectApi({
                data: data!.time,
                serial: device.value!.serial,
            }).then((res) => {
                console.log('发送数据成功：', res);
            }).catch((err) => {
                console.log('发送数据失败：', err);
            })
        })

        timeFlag.value = true
        if (timer) {
            clearInterval(timer)
        }
        timer = setInterval(() => {
            time.value--;
            console.log('剩余时间：', time.value);
            // 倒计时结束
            if (time.value <= 0) {
                clearTimer()
                closeKill();
                timeFlag.value = false

                timer = setInterval(() => {
                    router.back()
                }, device.value!.backViewTimeOut * 1000 * 60)
            }
        }, 1000);
    }
}
// 清除定时器
function clearTimer() {
    if (timer) {
        clearInterval(timer)
        clearTimeout(timer)
        timer = null
    }
    // if (readClosedTimer) {
    //     clearInterval(readClosedTimer)
    // }
}

async function addAlarm(msg: string,) {
    const time = getTime()
    db.error.add({
        time,
        info: msg,
    }).then(async () => {
        return await addAlarmApi({
            alarmType: msg,
            alarmData: time,
            serial: device.value!.serial
        })
    }).then(res => {
        if (res.code === 200) {
            console.log('取样超时报警记录发送成功！');
        } else {
            console.log('取样超时报警记录发送失败！');
        }
    }).catch(({ error, url, fetchOptions }) => {
        db.retryTasks.add({
            id: Date.now(),
            time: getTime(),
            url,
            info: fetchOptions
        }).then((id) => {
            console.log('重试任务添加取样超时记录成功', id);
        }).catch(err => {
            console.log('重试任务添加取样超时记录失败', err);
        })
    })
}

// 监听 testTube 表的数据变化
const subscription = liveQuery(
    () => db.testTube.toArray()
).subscribe({
    next: (data) => {
        console.log('testTube 数据变化:', data);
    },
    error: (error) => {
        console.error('监听出错:', error);
    }
});

const subscription2 = liveQuery(
    () => db.testTubeHistory.toArray()
).subscribe({
    next: (data) => {
        console.log('testTubeHistory 数据变化:', data);
    },
    error: (error) => {
        console.error('监听出错:', error);
    }
});

onMounted(async () => {
    device.value = await db.device.get(1) as device
    disinfectAutoMode.value = device.value.disinfectAutoMode
    disinfectTime.value = device.value.disinfectTime
    time.value = device.value.disinfectTime * 60
    currentTestTubeNum.value = await db.testTube.count()

    if (code === '999999') {
        name.value = 'admin'
        department.value = '管理'
    } else {
        nurse.value = await db.nurse.where({ info: code }).first() as nurse
        if (nurse.value) {
            name.value = nurse.value.name
            department.value = nurse.value.department
        } else {
            queryServiceNurseApi({
                serial: device.value.serial,
                info: code
            }).then(async ({ code, data }) => {
                console.log('查询护士信息成功:', data);
                if (data) {
                    name.value = data.name
                    department.value = data.department
                    return true
                } else {
                    return false
                }
            })
        }
    }
    // timer = setInterval(() => {
    //     router.back()
    // }, device.value!.backViewTimeOut * 1000 * 60)
})

onUnmounted(() => {
    if (timer) {
        clearInterval(timer)
    }
    subscription.unsubscribe();
    subscription2.unsubscribe();
})

window.onPhotoCapturedOut = (path: string) => {
    console.log('onPhotoCaptured', path);
    try {
        // 处理照片
        const file = processPhoto(path);
        // 保存到数据库
        savePhotoToDatabase(file, path,);
    } catch (error) {
        console.error('照片处理失败:', error);
    }
}

// 提取照片处理逻辑为独立函数
function processPhoto(path: string): File {
    console.log('处理照片路径:', path);
    const base64 = window.ClosetAndroid.readFileAsBase64(path)
    // 提取文件名
    const fileName = path.substring(path.lastIndexOf('/') + 1);
    const file = base64ToFile(base64, fileName);
    return file
}

// 提取数据库存储逻辑为独立函数
async function savePhotoToDatabase(file: File, path: string): Promise<void> {
    try {
        // 获取当前 testTube 表中的所有记录
        const currentTestTubes = await db.testTube.toArray();
        // 倒序查询最后 N 条 testTubeHistory 记录（N 为当前 testTube 数量）
        const historyRecords = await db.testTubeHistory
            .orderBy(':id')  // 按主键排序
            .reverse()       // 倒序
            .limit(currentTestTubes.length)  // 限制数量
            .toArray();

        // 反转数组以保证按正确顺序更新
        const orderedHistoryRecords = historyRecords.reverse();
        // 获取对应的 testTubeHistory 记录并更新
        await db.transaction('rw', db.testTubeHistory, async () => {
            for (const testTube of orderedHistoryRecords) {
                if (testTube) {
                    // 更新对应的 history 记录
                    await db.testTubeHistory.update(testTube.id, {
                        outImg: file,
                        outTime: getTime(),
                        outUrl: path
                    });
                }
            }
        });
        // 发送取样数据
        sendData(file, path)
        console.log('对应的 testTubeHistory 记录更新成功');
    } catch (err) {
        console.error('更新 testTubeHistory 记录失败:', err);
    }
}
// 发送取样数据
function sendData(file: File, path: string) {
    console.log('发送数据');
    uploadOutsFileApi({
        closetOuts: JSON.stringify({
            serial: device.value?.serial,
            tubeUse: 0,
            tubeRemain: device.value!.allNum - 0,
            data: {
                outData: getTime(),
                outInfo: nurse.value ? nurse.value.info : code,
                name: nurse.value ? nurse.value.name : name.value,
                department: nurse.value ? nurse.value.department : department.value,
                sex: nurse.value ? nurse.value.sex : '男',
                outUrl: path,
                birthday: nurse.value ? nurse.value.birthday : '1900-01-01',
            }
        }),
        file
    }).then(({ code, data }) => {
        // 清空现存取样记录
        db.testTube.clear()
        console.log('取样记录上传成功:', data);
    }).catch(({ error, url, fetchOptions }) => {
        console.log('out发送失败');
        console.log(error, url, fetchOptions);

        const file = fetchOptions.body.get('file') as File
        const closetPutsData = fetchOptions.body.get('closetOuts') as string
        // 处理 FormData 序列化问题
        db.retryTasks.add({
            id: Date.now(),
            time: getTime(),
            url,
            info: { closetOuts: closetPutsData },
            file
        }).then((id) => {
            console.log('重试任务添加取样成功', id);
        }).catch(err => {
            console.log('重试任务添加取样失败', err);
        })
    })
}
// 发送消毒记录
function sendDisinfectData() {
    addDisinfectApi({
        serial: device.value?.serial,
        data: getTime()
    }).then(({ code, data }) => {
        console.log('消毒记录上传成功:', data);
    })
}


onMounted(() => {
    window.TrackLockClosed = () => {
        console.log('轨道锁已关闭，消毒已开启');
        clearTimer()
        if (device.value?.disinfectAutoMode) {
            timeFlag.value = true
            setTimeout(() => {
                openKill()
                db.disinfect.add({
                    time: getTime(),
                    info: '自动模式消毒'
                }).then(() => { sendDisinfectData() })
            }, 1000);
            timer = setInterval(() => {
                time.value--;
                // 倒计时结束
                if (time.value <= 0) {
                    clearInterval(timer);
                    closeKill();
                    timeFlag.value = false
                    timer = setInterval(() => {
                        router.back()
                    }, device.value!.backViewTimeOut * 1000 * 60)
                }
            }, 1000);
        } else {
            timer = setInterval(() => {
                router.back()
            }, device.value!.backViewTimeOut * 1000 * 60)
        }
    }

    window.closeTrackLock = () => {
        closeDoorFn()
    }
})




</script>
<style lang="scss" scoped>
// $colors: #3498db, #2ecc71, #9b59b6, #e74c3c, #f39c12;
// $colors: #ff6b6b, #4ecdc4, #45b7d1, #f9ca24, #eb4d4b;
// $colors: #6c5ce7, #a29bfe, #fd79a8, #fdcb6e, #e17055;
// $colors: #00b894, #00cec9, #0984e3, #6c5ce7, #fdcb6e;
$colors: #00b894, #0984e3, #6c5ce7, #a29bfe, #fd79a8;

.container {
    width: 100%;
    height: 100vh;
    overflow: hidden;
    background: linear-gradient(135deg, #7fabb6 0%, #4aa0e8 50%, #dfbcf5 100%);


    // :deep(.ant-page-header-back) {
    //     font-size: .4rem;


    // }

    // :deep(.ant-page-header-heading-title) {
    //     font-size: .5rem;
    //     line-height: .6rem;
    // }

    .set {
        // background-color: red;
        width: 9rem;
        height: 9rem;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        display: grid;
        gap: .25rem;
        grid-template-areas:
            '. a a a a .'
            'b b d d c c'
            'b b d d c c'
            'b b d d c c'
            'b b d d c c'
            '. e e e e .'
        ;

        @for $i from 1 through length($colors) - 1 {
            .setItem#{$i} {
                $current-color: nth($colors, $i);
                $next-color: nth($colors, $i + 1);

                @if $i % 2 !=0 {
                    background: linear-gradient(to bottom, $current-color, $next-color);
                }

                @else {
                    background: linear-gradient(to right, $current-color, $next-color);
                }
            }
        }

        // 处理最后一个元素（可选）
        .setItem#{length($colors)} {
            $last-color: nth($colors, length($colors));
            $first-color: nth($colors, 1);
            background: linear-gradient(to right, $last-color, $first-color);
        }


        .item {
            width: 100%;
            height: 100%;
            display: flex;
            justify-content: center;
            align-items: center;
            border-radius: .125rem;
            color: #fff;
            font-size: .5rem;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;

            img {
                height: 1rem;
                aspect-ratio: 1;
                margin-bottom: .125rem;
            }
        }

    }
}
</style>